package com.wondertek.poms.service.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.wondertek.poms.common.constant.Constants;
import com.wondertek.poms.common.constant.CurrentUser;
import com.wondertek.poms.common.exception.MessageCodes;
import com.wondertek.poms.common.log.MethodLog;
import com.wondertek.poms.common.utils.LocalDateTimeUtils;
import com.wondertek.poms.common.utils.excel.ExportExcel;
import com.wondertek.poms.common.utils.excel.ImportExcel;
import com.wondertek.poms.common.utils.validate.ValidateFilter;
import com.wondertek.poms.common.vo.PageBean;
import com.wondertek.poms.common.vo.ResultBean;
import com.wondertek.poms.core.service.IBcInfoService;
import com.wondertek.poms.dao.po.BcInfo;
import com.wondertek.poms.dao.pojo.BcInfoExcelPojo;
import com.wondertek.poms.service.vo.BcInfoVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @author evan0213
 * @description
 */
@Api(value = "BcInfoController", description = "播控方管理 接口")
@RestController
@RequestMapping("bc-info")
public class BcInfoController {

	@Autowired
	private IBcInfoService bcInfoService;

	/**
	 * 播控方下拉列表
	 *
	 * @return 全量播控方列表
	 */
	@ApiOperation(value = "播控方 全量", notes = "播控方 全量")
	@GetMapping("/all")
	@MethodLog(module = "播控方全量")
	public ResultBean all() {
		List<BcInfo> all = bcInfoService.findAll();
		return ResultBean.ok(all);
	}

	/**
	 * 播控方分页查询
	 *
	 * @param bcInfoVo 查询条件
	 * @param page     页码
	 * @param rows     条目
	 * @param sidx     列名
	 * @param sord     升序/降序
	 * @return 分页查询结果
	 */
	@ApiOperation(value = "播控方 列表", notes = "查询播控方")
	@GetMapping("/list")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "bcId", required = false),
			@ApiImplicitParam(name = "name", required = false)
	})
	public ResultBean list(BcInfoVo bcInfoVo,
						   @RequestParam(defaultValue = "1") int page,
						   @RequestParam(defaultValue = "20") int rows,
						   @RequestParam(defaultValue = "creatTime") String sidx,
						   @RequestParam(defaultValue = "desc") String sord) {
		BcInfo bcInfo = new BcInfo();
		BeanUtils.copyProperties(bcInfoVo, bcInfo);
		Page<BcInfo> pages = bcInfoService.findAll(bcInfo, page, rows, sidx, sord);
		return PageBean.ok(pages.getTotalPages(), pages.getTotalElements(), pages.getContent());
	}

	/*
	 * 播控方 详情
	 * @param id 记录id
	 * @return 记录查询结果
	 */
	@ApiOperation(value = "播控方 详情", notes = "查询播控列表详情")
	@ApiImplicitParam(name = "id", required = true, paramType = "query", dataType = "Long")
	@GetMapping("/get")
	public ResultBean get(Long id) {
		return ResultBean.ok(bcInfoService.get(id));
	}

	/*
	 * 播控方 新增
	 * @param bcInfoVo 记录信息
	 * @return ok
	 */
	@ApiOperation(value = "播控方 新增", notes = "新增播控列表记录")
	@PostMapping("/add")
	public ResultBean add(@RequestBody BcInfoVo bcInfoVo) {
		List<String> messageList = ValidateFilter.getFilterMessage(bcInfoVo, Constants.VALIDATE_DEFAULT);
		if (!messageList.isEmpty()) {
			return ResultBean.error(messageList.toString());
		}
		if (isRepeat(bcInfoVo)) {
			return ResultBean.error(MessageCodes.get(MessageCodes.M980014));
		}
		BcInfo bcInfo = new BcInfo();
		BeanUtils.copyProperties(bcInfoVo, bcInfo);
		bcInfo.setCreator(CurrentUser.currUserName());
		bcInfo.setCreatTime(LocalDateTimeUtils.localDateFormat(LocalDateTime.now(), "yyyy-MM-dd HH:mm:ss"));
		bcInfoService.save(bcInfo);
		return ResultBean.ok();
	}

	/*
	 * 播控方 删除
	 * @param ids 删除记录id，多个用英文逗号连接
	 * @return ok
	 */
	@DeleteMapping(value = "/del")
	@ApiOperation(value = "播控方 删除", notes = "批量删除播控列表记录")
	@ApiImplicitParam(name = "ids", required = true, dataType = "String", value = "删除播控列表记录,主键id拼接字符串,以英文逗号分隔")
	public ResultBean del(String ids) {
		if (StringUtils.isNotBlank(ids)) {
			String[] idArray = ids.split(",");
			List<Long> idList = Arrays.stream(idArray).distinct().map(Long::parseLong).collect(Collectors.toList());
			idList.forEach(id -> bcInfoService.deleteById(id));
		}
		return ResultBean.ok();
	}

	/*
	 * 播控方 编辑
	 * @param bcInfoVo 更新记录信息
	 * @return ok
	 */
	@ApiOperation(value = "播控方 编辑", notes = "编辑版权所属cp")
	@PutMapping(value = "/edit")
	public ResultBean edit(@RequestBody BcInfoVo bcInfoVo) {
		List<String> messageList = ValidateFilter.getFilterMessage(bcInfoVo, Constants.VALIDATE_UPDATE);
		if (!messageList.isEmpty()) {
			return ResultBean.error(messageList.toString());
		}
		if (isRepeat(bcInfoVo)) {
			return ResultBean.error(MessageCodes.get(MessageCodes.M980014));
		}

		BcInfo bcInfo = bcInfoService.findById(bcInfoVo.getId());
		BeanUtils.copyProperties(bcInfoVo, bcInfo);
		//bcInfo.setUpdateTime();
		//bcInfo.setUpdator();
		bcInfoService.save(bcInfo);
		return ResultBean.ok();
	}

	/**
	 * 播控方 导出
	 * @param bcInfoVo 搜索信息
	 * @param sidx 排序列
	 * @param sord 排序方式
	 * @param response 请求
	 * @return 结果
	 */
	@ApiOperation(value = "播控方 导出", notes = "导出播控方excel文件")
	@PostMapping(value = "/export")
	public ResultBean exportCpInfo(BcInfoVo bcInfoVo,
								   @RequestParam(defaultValue = "creatTime") String sidx,
								   @RequestParam(defaultValue = "desc") String sord,
								   HttpServletResponse response) {
		ExportExcel exportExcel = new ExportExcel("播控方数据导出", BcInfoExcelPojo.class, 1);
		BcInfo bcInfo = new BcInfo();
		BeanUtils.copyProperties(bcInfoVo, bcInfo);
		List<BcInfo> lists = bcInfoService.findAll(bcInfo,sidx,sord);
		List<BcInfoExcelPojo> pojos = lists.stream().map(bcInfo1->{
			BcInfoExcelPojo bcInfoExcelPojo = new BcInfoExcelPojo();
			BeanUtils.copyProperties(bcInfo1, bcInfoExcelPojo);
			return bcInfoExcelPojo;
		}).collect(Collectors.toList());
		try {
			exportExcel.setDataList(pojos);
			exportExcel.write(response,  "BcInfo"+ "cpInfo_"+ LocalDateTimeUtils.localDateFormat(LocalDateTime.now(), "yy-MM-dd HH:mm:ss") + ".xlsx");
		} catch (Exception e) {
			e.printStackTrace();
			return ResultBean.error(MessageCodes.get(MessageCodes.M980000));
		}
		return ResultBean.ok();
	}

	/**
	 * 播控方 导入
	 * @param file excel文件
	 * @return
	 */
	@ApiOperation(value = "播控方 导入", notes = "导入播控方excel文件")
	@PostMapping(value = "/import")
	public ResultBean importCpInfo(MultipartFile file) {
		StringBuffer msg = new StringBuffer("导入数据总数->");
		StringBuffer errMessage = new StringBuffer(".错误原因是->");
		AtomicInteger errNum = new AtomicInteger();// 全局错误数
		List<BcInfoExcelPojo> list = new ArrayList<>();
		try {
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<BcInfoExcelPojo> dataList = ei.getDataList(BcInfoExcelPojo.class);
			if (CollectionUtil.isNotEmpty(dataList)){
				msg.append(dataList.size() + ".错误数据数->");
				dataList.forEach(v -> importData(errMessage, errNum, v, list));
			}else {
				return ResultBean.error(MessageCodes.get(MessageCodes.M980205));
			}
			if(CollectionUtil.isNotEmpty(list)){
				for(BcInfoExcelPojo pojo : list){
					BcInfo bcInfo = new BcInfo();
					BeanUtils.copyProperties(pojo, bcInfo);
					bcInfoService.save(bcInfo);
				}
			}
			msg.append(errNum);
			msg.append(errMessage);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultBean.error(MessageCodes.get(MessageCodes.M980000));
		}
		if (errNum.get() > 0) {
			return ResultBean.error(msg.toString().replace("[", "").replace("]", "").replace("[]", "").replace("!", ""));
		}
		return ResultBean.ok();
	}

	private Boolean isRepeat(BcInfoVo bcInfoVo) {
		BcInfo temp = new BcInfo();
		temp.setName(bcInfoVo.getName());
		Optional<BcInfo> opt = bcInfoService.findOne(Example.of(temp));
		if (opt.isPresent()) {
			BcInfo bcInfo = opt.get();
			if (bcInfoVo.getId() != null && !bcInfo.getId().equals(bcInfoVo.getId())) {
				return true;
			}
			if (bcInfoVo.getId() == null) {
				return true;
			}
		}
		BcInfo temp1 = new BcInfo();
		temp1.setBcId(bcInfoVo.getBcId());
		Optional<BcInfo> opt1 = bcInfoService.findOne(Example.of(temp1));
		if (opt1.isPresent()) {
			BcInfo bcInfo = opt1.get();
			if (bcInfoVo.getId() != null && !bcInfo.getId().equals(bcInfoVo.getId())) {
				return true;
			}
			if (bcInfoVo.getId() == null) {
				return true;
			}
		}

		return false;
	}

	public void importData(StringBuffer errMessage, AtomicInteger errNum, BcInfoExcelPojo pojo, List<BcInfoExcelPojo> list) {
		if (pojo != null) {
			Boolean flag = true;
			List<String> messageList = ValidateFilter.getFilterMessage(pojo, Constants.VALIDATE_DEFAULT);
			flag = checkData(errMessage, errNum, pojo, flag, messageList,list);

			if (flag) {
				list.add(pojo);
			}
		}
	}

	public Boolean checkData(StringBuffer errMessage, AtomicInteger errNum, BcInfoExcelPojo pojo, Boolean flag, List<String> messageList, List<BcInfoExcelPojo> list) {
		if (flag && !messageList.isEmpty()) {
			errNum.addAndGet(1);
			flag = false;
			errMessage.append("导入出错：" + messageList.toString() + ".  ");
		}
		if (flag) {//如果已经传入的list里有重复的id或者name 也拒绝
			List<BcInfoExcelPojo> data = list.stream().filter(bcInfoExcelPojo ->
					bcInfoExcelPojo.getBcId().equals(pojo.getBcId()) || bcInfoExcelPojo.getName().equals(pojo.getName()))
					.collect(Collectors.toList());
			if (data.size() > 0) {
				errNum.addAndGet(1);
				flag = false;
				errMessage.append("播控方id：" + pojo.getBcId() + " 播控方名称：" + pojo.getName() + " 导入出错：" + MessageCodes.get(MessageCodes.M980014) + ".  ");
				return flag;
			}


			BcInfoVo bcInfoVo = new BcInfoVo();
			bcInfoVo.setBcId(pojo.getBcId());
			bcInfoVo.setName(pojo.getName());

			if (isRepeat(bcInfoVo)) {
				errNum.addAndGet(1);
				flag = false;
				errMessage.append("播控方id：" + pojo.getBcId() + " 播控方名称：" + pojo.getName() + " 导入出错：" + MessageCodes.get(MessageCodes.M980014) + ".  ");
			}

		}
		return flag;

	}


}
